﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;
using System.Web.Security;

namespace SEP.Admin
{
    public partial class ServiceReportView : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                Guid jobID = Guid.Empty;

                if(Request.QueryString["jobid"] != null)
                {                    
                    this.BindData(GetJobID());
                }
                else
                {
                    btnCreateServiceReport.Visible = false;
                }
            }
        }

        private void BindData(Guid jobID)
        {            
            Job j = new Job();
            j = j.GetByID(jobID);

            lblJobInfo.Text = j.FullName;

            if(j.Location != null)
            {
                lblLocationContact.Text = j.Location.PrimaryContact.Name;            
                lblLocationEmail.Text = j.Location.EmailAddress.EmailAddress;
                lblLocationFacility.Text = j.Location.Name;
                lblLocationFax.Text = j.Location.Phones.First(x => x.PhoneTypeAsString.Equals("Fax")).Number;
                lblLocationPhone.Text = j.Location.Phone.FormattedNumberWithExtension;
                lblLocationStreet.Text = j.Location.Address.AddressBlock.Replace("<br /><br />", "<br />");
                lblLocationCityStateZip.Text = string.Concat(j.Location.Address.City, ", ", j.Location.Address.State.Abbreviation, " ", j.Location.Address.PostCode).Trim();
            }

            if (j.BillTo != null)
            {
                lblBillToContact.Text = j.BillTo.PrimaryContact.Name;
                lblBillToEmail.Text = j.BillTo.EmailAddress.EmailAddress;
                lblBillToFacility.Text = j.BillTo.Name;
                lblBillToFax.Text = j.BillTo.Phones.First(x => x.PhoneTypeAsString.Equals("Fax")).Number;
                lblBillToPhone.Text = j.BillTo.Phone.FormattedNumberWithExtension;
                lblBillToStreet.Text = j.BillTo.Address.AddressBlock.Replace("<br /><br />", "<br />");
                lblBillToCityStateZip.Text = string.Concat(j.BillTo.Address.City, ", ", j.BillTo.Address.State.Abbreviation, " ", j.BillTo.Address.PostCode).Trim();
            }

            List<ServiceReport> summaries = j.ServiceReports; 
            
            grvServiceReports.DataSource = summaries;
            grvServiceReports.DataBind();            

            if(j.Archived)
            {
                btnFinalize.Enabled = false;
                btnFinalize.Text = "Archived";
                
                j.SentToIan = true;
                j.SentToJenny = true;

                btnCreateServiceReport.Visible = false;
            }

            if(j.SentToIan)
            {
                btnSendToIan.Enabled = false;
                btnSendToIan.Text = "Already sent to Ian";
            }

            if(j.SentToJenny)
            {
                btnSendToJenny.Enabled = false;
                btnSendToJenny.Text = "Already sent to Jenny";
            }            
        }

        protected void grvServiceReports_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            string id = grvServiceReports.SelectedDataKey.Value.ToString(); //grvServiceReports.DataKeyNames[];

            Response.Redirect(string.Format("~/Admin/ServiceReportViewDetail.aspx?id={0}", id));
        }

        protected void grvServiceReports_OnRowEditing(object sender, GridViewEditEventArgs e)
        {
            string id = grvServiceReports.DataKeys[e.NewEditIndex].Value.ToString();

            Response.Redirect(string.Format("~/Admin/ServiceReport.aspx?id={0}", id));            
        }
        
        private Guid GetJobID()
        {
            Guid jobID = Guid.Empty;

            if (Request.QueryString["jobID"] != null)
            {
                jobID = new Guid(Request.QueryString["jobID"].ToString());
            }

            return jobID;
        }

        protected void btnSendToIan_Click(object sender, EventArgs e)
        {
            Guid jobID = GetJobID();

            Job.SendToIan(jobID);    
            BindData(jobID);
        }

        protected void btnSendToJenny_Click(object sender, EventArgs e)
        {
            Guid jobID = GetJobID();

            Job.SendToJenny(jobID);
            BindData(jobID);
        }

        protected void btnFinalize_Click(object sender, EventArgs e)
        {
            Guid jobID = GetJobID();

            Job.Finalize(jobID);
            BindData(jobID);
        }

        protected void btnCreateServiceReport_Click(object sender, EventArgs e)
        {
            Response.Redirect(string.Format("~/Admin/ServiceReport.aspx?jobID={0}", GetJobID()));
        }

        protected void lnkBtnExportExcel_OnCommand(object sender, CommandEventArgs e)
        {
            Guid serviceReportID = new Guid();

            if (Guid.TryParse(e.CommandArgument.ToString(), out serviceReportID))
            {
                ServiceReport sr = ServiceReport.GetByID(serviceReportID);
                sr.TemplatePath = Server.MapPath(ExcelTemplates.TEMPLATE);

                if(sr != null)
                {
                    byte[] arr = ServiceReport.CreateExcel(sr);

                    Response.Clear();
                    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
                    Response.AddHeader("content-length", arr.Length.ToString());
                    Response.BinaryWrite(arr);
                }
            }
        }

        protected void grvServiceReports_OnRowDataBound(object sender, GridViewRowEventArgs e) 
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");
                l.Attributes.Add("onclick", "javascript:return confirm('You are about to delete this service report?')");
            }
        }

        protected void grvServiceReports_DeleteRecord(object sender, GridViewDeleteEventArgs e) 
        {
            string temp = grvServiceReports.DataKeys[e.RowIndex].Value.ToString();

            if (!string.IsNullOrWhiteSpace(temp))
            {   
                Guid id = new Guid();

                if(Guid.TryParse(temp, out id))
                {
                    if (id != Guid.Empty)
                    {
                        try
                        {
                            ServiceReport.Delete(id);
                        }
                        catch (Exception ex) { }
                    }

                    BindData(GetJobID());
                }
            }            
        }
    }
} 